<?php
namespace App\Service\Member;

class TiebaService extends BaseService
{
    //贴吧

    /**
     * 帖子列表
     * @param array $pages【start，limit】
     */
    public function getList($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbTieba)
            ->where('del', 0);
        if (isset($pas['utype']) && $pas['utype']) {
            $db = $db->where('utype', 1);
        }
        if (isset($pas['cate_id']) && $pas['cate_id']) {
            $db = $db->where('cate_id', $pas['cate_id']);
        }
        if (isset($pas['is_follow']) && $pas['is_follow']) {
            $uOnes = $this->dbConn($this->dbUfollow)
                ->where('uid', $pas['uid'])
                ->get();
            if (count($uOnes)) {
                $uids = [];
                foreach ($uOnes as $v) {
                    $uids[] = $v->uid_ed;
                }
            $db = $db->whereIn('uid', $uids);
            }
        }
        if (isset($pas['is_recommend']) && $pas['is_recommend']) {
            $blks = $this->dbConn($this->dbPatient)
                ->where('uid', $pas['uid'])
                ->get();
            if (count($blks)) {
                $cateids = [];
                foreach ($blks as $v) {
                    $cateids[] = $v->cate_id;
                }
                $db = $db->whereIn('cate_id', $cateids);
            }
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('read_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uname = ''; $uhead = ''; $utype_name = '-';
            $seek_type = 0;
            //用户
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['uid'])
                ->first();
            if (!empty($uOne) && $uOne['uname']) {
                $uname = $uOne['uname'];
            }
            if (!empty($uOne)) {
                $utype_name = $uOne['utype'] == 1 ? '患者' : '医生';
            }
            if (!empty($uOne) && file_exists($uOne['head'])) {
                $uhead = env('DOMAIN') . '/' . $uOne['head'];
            }
            $doctorOne = (array) $this->dbConn($this->dbDoctor)
                ->where('del', 0)
                ->where('uid', $v['uid'])
                ->first();
            if (!empty($doctorOne)) {
                //科室
                $departOne = (array) $this->dbConn($this->dbCate)
                    ->where('del', 0)
                    ->where('id', $doctorOne['cate_id'])
                    ->first();
                //头衔
                $workTitleOne = (array) $this->dbConn($this->dbCate)
                    ->where('del', 0)
                    ->where('id', $doctorOne['work_title'])
                    ->first();
                $seek_type = $doctorOne['seek_type'];
            }
            $keshi = empty($departOne) ? '-' : $departOne['title'];
            $work_title_name = empty($workTitleOne) ? '-' : $workTitleOne['title'];
            $desc = mb_strlen($v['cnt'])>50 ? mb_substr($v['cnt'], 0, 50).'...' : $v['cnt'];
            $riqi = $v['addtime'] ? explode(' ', $v['addtime'])[0] : '-';
            //回复数量
            $reply_num = $this->dbConn($this->dbTbReply)
                ->where('del', 0)
                ->where('tiezi', $v['id'])
                ->count();
            //点赞数量
            $like_num = $this->dbConn($this->dbTbLike)
                ->where('tiezi', $v['id'])
                ->where('reply', 0)
                ->count();
            //分类
            $cateOne = (array) $this->dbConn($this->dbCate)
                ->where('del', 0)
                ->where('id', $v['cate_id'])
                ->first();
            $cate_name = empty($cateOne) ? '-' : $cateOne['title'];
            //是否支付
            $is_pay = 0; //0未支付，1免费或已支付
            if (!$v['read_cost']) {
                $is_pay = 1;
            } else {
                $tbPay = (array) $this->dbConn($this->dbTbPay)
                    ->where('tiezi', $v['id'])
                    ->where('uid', $pas['uid'])
                    ->first();
                if (!empty($tbPay) && $tbPay['is_pay'] == 2) {
                    $is_pay = 1;
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'uid'=>$v['uid'],
                'uname' => $uname, 'uhead' => $uhead,
                'keshi' => $keshi, 'work_title_name' => $work_title_name,
                'utype_name' => $utype_name, 'seek_type' => $seek_type,
                'title' => $v['title'], 'desc' => $desc,
                'riqi' => $riqi, 'cate_name' => $cate_name,
                'read_num' => $v['read_num'],
                'reply_num' => $reply_num,
                'like_num' => $like_num,
                'read_cost' => toNumber($v['read_cost']),
                'area_name' => '杭州市',
                'last_pub' => $this->getLast($v['addtime']),
                'is_pay' => $is_pay,
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 帖子详情
     */
    public function getOne($id, $uid)
    {
        $res = (array) $this->dbConn($this->dbTieba)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        //用户
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('id', $res['uid'])
            ->first();
        $uname = '-'; $uhead = ''; $utype_name = '-';
        if (!empty($uOne) && $uOne['uname']) {
            $uname = $uOne['uname'];
        }
        if (!empty($uOne)) {
            $utype_name = $uOne['utype'] == 1 ? '患者' : '医生';
        }
        if (!empty($uOne) && file_exists($uOne['head'])) {
            $uhead = env('DOMAIN') . '/' . $uOne['head'];
        }
        //医生信息
        $doctorOne = (array) $this->dbConn($this->dbDoctor)
            ->where('del', 0)
            ->where('uid', $res['uid'])
            ->first();
//        $seekType = !empty($doctorOne)&&$doctorOne['seek_type'] ? $doctorOne['seek_type'] : 0;
        //科室
        $departOne = (array) $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('id', $doctorOne['cate_id'])
            ->first();
        $keshi = empty($departOne) ? '-' : $departOne['title'];
        //头衔
        $workTitleOne = (array) $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('id', $doctorOne['work_title'])
            ->first();
        $work_title_name = empty($workTitleOne) ? '-' : $workTitleOne['title'];
        //费用
//        $configOne = (array) $this->dbConn($this->dbUdSeek)
//            ->where('del', 0)
//            ->where('doctor_id', $res['uid'])
//            ->where('seek_id', $seekType)
//            ->orderBy('id', 'desc')
//            ->first();
//        $price = !empty($configOne)&&$configOne['price'] ?
//            toNumber($configOne['price']) . $configOne['unit'] : '-';
        $price = toNumber($res['read_cost']);
        $riqi = $res['addtime'] ? explode(' ', $res['addtime'])[0] : '-';
        //回复数量
        $reply_num = $this->dbConn($this->dbTbReply)
            ->where('del', 0)
            ->where('tiezi', $res['id'])
            ->count();
        //分类
        $cateOne = (array) $this->dbConn($this->dbCate)
            ->where('del', 0)
            ->where('id', $res['cate_id'])
            ->first();
        $cate_name = empty($cateOne) ? '-' : $cateOne['title'];
        //是否点赞
        $likeOne = (array) $this->dbConn($this->dbTbLike)
            ->where('tiezi', $id)
            ->where('uid', $uid)
            ->first();
        //点赞量
        $like_num = $this->dbConn($this->dbTbLike)
            ->where('tiezi', $id)
            ->where('reply', 0)
            ->where('uid', $uid)
            ->count();
        //是否已支付
        $is_pay = 0; //0未支付，1已支付或免费
        if (!$res['read_cost']) {
            $is_pay = 1;
        } else {
            $payOne = (array) $this->dbConn($this->dbTbPay)
                ->where('tiezi', $id)
                ->where('uid', $uid)
                ->where('is_pay', 2)
                ->first();
            $is_pay = empty($payOne) ? 0 : 1;
        }
        $arys = [
            'id' => $res['id'],
            'uid' => $res['uid'],
            'uname' => $uname, 'uhead' => $uhead,
            'keshi' => $keshi, 'work_title_name' => $work_title_name,
            'utype_name' => $utype_name, 'price' => $price,
            'title' => $res['title'], 'cnt' => $res['cnt'],
            'riqi' => $riqi, 'cate_name' => $cate_name,
            'read_num' => $res['read_num'],
            'reply_num' => $reply_num,
            'is_like' => empty($likeOne) ? 0 : 1,
            'like_num' => $like_num,
            'is_pay' => $is_pay,
            'to_pay' => [
                'yw_type' => 2,
                'yw_id' => $res['id'],
            ],
        ];
        return $this->toback(0, '', $arys);
    }

    //时间转时分秒
    public function getLast($addtime)
    {
        $lasttime = time() - strtotime($addtime);
        $day = intval($lasttime / 3600 / 24);
        $hour = intval(($lasttime - $day * 3600 * 24) / 3600);
        $fen = intval(($lasttime - $day * 3600 * 24 -  $hour * 3600) / 60);
        $last_pub = '';
        if ($day) { $last_pub = $day.'天'; }
        if ($hour) { $last_pub .= $hour.'小时'; }
        if ($fen) { $last_pub .= $fen.'分'; }
        return $last_pub.'前';
    }

    //医生发布
    public function doctorAdd($pas)
    {
        $pas['utype'] = 1;
        $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbTieba)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        $ary = [
            'yw_type' => 2,
            'yw_id' => $lastid,
        ];
        return $this->toback(0, '', $ary);
    }

    //发布
    public function add($pas)
    {
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('id', $pas['uid'])
            ->first();
        if (empty($uOne)) {
            return $this->toback(-2, '没有登录');
        }
        $cateOne = (array) $this->dbConn($this->dbCate)
            ->where('id', $pas['cate_id'])
            ->first();
        if (empty($cateOne)) {
            return $this->toback(-2, '没有类型');
        }
        $pas['utype'] = $uOne['utype'];
        if(!isset($pas['title'])||!$pas['title']){
            $pas['title'] = $cateOne['title'].toUname();
        }
        $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbTieba)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        $ary = [
            'yw_type' => 2,
            'yw_id' => $lastid,
        ];
        return $this->toback(0, '', $ary);
    }

    /**
     * 帖子删除
     * @param int $id
     */
    public function del($id)
    {
        $res = (array) $this->dbConn($this->dbTieba)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbTieba)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 评论列表
     * @param array $pages【start，limit】
     */
    public function replyList($tiezi, $pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbTbReply)
            ->where('del', 0)
            ->where('tiezi', $tiezi)
            ->where('pid', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //用户信息
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['uid'])
                ->first();
            $uname = '-';
            $uhead = '';
            $utype_name = '-';
            if (!empty($uOne) && $uOne['uname']) {
                $uname = $uOne['uname'];
            }
            if (!empty($uOne) && file_exists($uOne['head'])) {
                $uhead = env('DOMAIN') . '/' . $uOne['head'];
            }
            if (!empty($uOne)) {
                $utype_name = $uOne['utype']==1 ? '患者' : '医生';
            }
            //子评论
            $childList = [];
            $childOnes = $this->dbConn($this->dbTbReply)
                ->where('del', 0)
                ->where('tiezi', $tiezi)
                ->where('pid', $v['id'])
                ->get();
            //是否点赞
            $likeOne = (array) $this->dbConn($this->dbTbLike)
                ->where('tiezi', $tiezi)
                ->where('reply', $v['id'])
                ->where('uid', $uid)
                ->first();
            if (count($childOnes)) {
                foreach ($childOnes as $vv) {
                    $vv = (array) $vv;
                    //用户信息
                    $uOne2 = (array) $this->dbConn($this->dbUser)
                        ->where('id', $vv['uid'])
                        ->first();
                    $uname2 = '';
                    $utype2 = 0; $utype_name2 = '患者';
                    if (!empty($uOne2) && $uOne2['uname']) {
                        $uname2 = $uOne2['uname'];
                    }
                    if (!empty($uOne2) && $uOne2['utype']) {
                        $utype2 = $uOne2['utype'];
                        $utype_name2 = $uOne2['utype']==1 ? '患者' : '医生';
                    }
                    //是否点赞
                    $likeOne2 = (array) $this->dbConn($this->dbTbLike)
                        ->where('tiezi', $tiezi)
                        ->where('reply', $vv['id'])
                        ->where('uid', $uid)
                        ->first();
                    $childList[] = [
                        'id' => $vv['id'],
                        'cnt' => $vv['cnt'],
                        'uname' => $uname2,
                        'utype_name' => $utype_name2,
                        'is_like' => empty($likeOne2) ? 0 : 1,
                    ];
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'cnt' => $v['cnt'],
                'uname' => $uname,
                'uhead' => $uhead,
                'utype_name' => $utype_name,
                'like_num' => $v['like_num'],
                'is_like' => empty($likeOne) ? 0 : 1,
                'last_pub' => $this->getLast($v['addtime']),
                'childList' => $childList,
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //评论发布
    public function replyAdd($pas)
    {
        $tieziOne = (array) $this->dbConn($this->dbTieba)
            ->where('del', 0)
            ->where('id', $pas['tiezi'])
            ->first();
        if (empty($tieziOne)) {
            return $this->toback(-2, '没有帖子');
        }
        $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbTbReply)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //点赞
    public function likeAdd($tiezi, $plid, $uid)
    {
        $res = (array) $this->dbConn($this->dbTbLike)
            ->where('tiezi', $tiezi)
            ->where('reply', $plid)
            ->where('uid', $uid)
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '已点赞');
            //return $this->toback();
        }
        $lastid = $this->dbConn($this->dbTbLike)->insertGetId([
            'tiezi' => $tiezi, 'reply' => $plid,
            'uid' => $uid, 'addtime' => toDate(),
        ]);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}
